package com.boil.qz.safekavass.shiro.filter;

import com.boil.util.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by ChenYong on 2017-04-14.
 * <br>
 * 请求类型过滤器。
 * <br>
 * 判断请求类型：Ajax 请求/JSON 请求/普通请求。
 */
public class RequestTypeFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 获取请求
        HttpServletRequest request1 = (HttpServletRequest) request;
        // 获取登录用户的操作信息
        Subject subject = SecurityUtils.getSubject();
        // 获取 Session
        Session session = subject.getSession();
        // 请求路径
        String servletPath = (StringUtils.isBlank(request1.getServletPath()) ? Constants.EMPTY_STR : request1.getServletPath());

        // 如果是非 403 请求，判断请求类型：Ajax 请求/JSON 请求/普通请求
        if (!Constants.URL_403.equals(servletPath) && !Constants.URL_403_1.equals(servletPath)) {
            // Ajax 请求
            if (Constants.AJAX_REQUEST.equalsIgnoreCase(request1.getHeader(Constants.REQUEST_TYPE))) {
                session.setAttribute(Constants.REQUEST_TYPE_STR, Constants.VALUE_2);

                // JSON 请求
            } else if (servletPath.endsWith(Constants.SUFFIX_JSON)) {
                session.setAttribute(Constants.REQUEST_TYPE_STR, Constants.VALUE_3);

                // 普通请求
            } else {
                session.setAttribute(Constants.REQUEST_TYPE_STR, Constants.VALUE_1);
            }
        }

        chain.doFilter(request, response);
    }
}